﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace FolderFileMenu
{
    public class DateCompareFileInfo : IComparer<FileInfo>
    {
        //public int Compare(FileInfo fi1, FileInfo fi2)
        //{
        //    int result;
        //    if (fi1.LastWriteTime == fi2.LastWriteTime) { result = 0; }
        //    else if (fi1.LastWriteTime < fi2.LastWriteTime) { result = 1; }
        //    else { result = -1; }
        //    return result;
        //}
        public int Compare(FileInfo fi1, FileInfo fi2)
        {
            int result;
            if (fi1.LastAccessTime == fi2.LastAccessTime) { result = 0; }
            else if (fi1.LastAccessTime < fi2.LastAccessTime) { result = 1; }
            else { result = -1; }
            return result;
        }
    }

    public class PathCompareFileInfo : IComparer<FileInfo>
    {
        public int Compare(FileInfo fi1, FileInfo fi2)
        {
            if ((string.Compare(fi1.DirectoryName, fi2.DirectoryName)) == 0)
            {
                return (string.Compare(fi1.Name, fi2.Name)); // sort alphabetically
            }
            else { return -1; }
        }
    }

    public static class WildcardMatch
    {   /*
         * DOS/Windows:
         * ¯¯¯¯¯¯¯¯¯¯¯
         * The asterisk pattern character (*, also called "star") matches zero or more characters.
         * The question mark matches exactly one character - except missing characters at the end.
         * 
         * RegularExpression:
         * ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
         * A dot matches any single character which is not part of a newline (`r`n) sequence.
         * An asterisk matches zero or more of the preceding character, class, or subpattern.
         * A question mark matches zero or one of the preceding character, class, or subpattern.
         
         * Substitution:
         * ¯¯¯¯¯¯¯¯¯¯¯¯
         * The wildcard * is equivalent to the Regex pattern ".*" (greedy) or ".*?" (not-greedy).
         * With ^ on start and $ at end, regex only find matches where the entire string matches.
         */
        public static bool IsLike(string pattern, string text, bool caseSensitive = false)
        {
            pattern = pattern.Replace("?", ".");
            pattern = pattern.Replace("*", ".*?");
            if (pattern.EndsWith(".*?"))
            {
                pattern = pattern.Remove(pattern.Length - 3, 3);
                pattern += ".*";
            }
            return new Regex("^" + pattern + "$", caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase).IsMatch(text);
        }
    }

}
